#include "../include/aj_sessioninfo_list.h"

SessionInfoList::SessionInfoList()
{

}

SessionInfoList::~SessionInfoList()
{
    Clear();
}

SessionInfo *SessionInfoList::NewSessionInfo(std::shared_ptr<NETAPI::TcpSession> &session)
{
    std::lock_guard<std::mutex> lock(m_lock);
    SessionInfo *info = new SessionInfo(session);
    m_list.push_back(info);
    info->OnDisConnected = std::bind(&SessionInfoList::SessionDisconnected,
        this,
        std::placeholders::_1);
    return info;
}

void SessionInfoList::Clear()
{
    std::lock_guard<std::mutex> lock(m_lock);
    for (SessionInfo* info : m_list)
    {
        if (info)
            info->deleteLater();
    }
    m_list.clear();
}

SessionInfo *SessionInfoList::FindByID(const void *id)
{
    if (!id)
        return nullptr;
    std::lock_guard<std::mutex> lock(m_lock);
    for (size_t i = 0; i < m_list.size(); ++i)
    {
        SessionInfo *info = m_list[i];
        if (info == id)
            return info;
    }
    return nullptr;
}

SessionInfo *SessionInfoList::FindByIP(QString ip)
{
    if ("" == ip)
    {
        return nullptr;
    }
    std::lock_guard<std::mutex> lock(m_lock);
    for (size_t i = 0; i < m_list.size(); ++i)
    {
        SessionInfo *info = m_list[i];
        if (nullptr == info)
        {
            continue;
        }
        QString strIp = info->getIp();
        //if (strIp.contains(ip))
        if (strIp == ip)//contains bu xing
        {
            return info;
        }
    }
    return nullptr;
}

void SessionInfoList::SessionDisconnected(void *id)
{
    SessionInfo *info = nullptr;
    std::lock_guard<std::mutex> lock(m_lock);
    //将session从列表中删除
    std::vector<SessionInfo*>::iterator it;
    for (it = m_list.begin(); it != m_list.end(); ++it)
    {
        info = *it;
        if (info == id)
        {
            it = m_list.erase(it);
            info->OnDisConnected = nullptr;
            info->deleteLater();
            //delete info;
            qDebug()<<QString("%1----delete").arg(m_list.size());
            return;
        }
    }
}
